<?php

    global $mikron;
    $mikron->Schema->Add(dirname(__FILE__).'/schema.xml', 'Схема избранного');
    $mikron->OperatingInstructions->AddFunction('MIKRON_FAVOURITE', 'OperatingInstruction_MikronFavourites');

    /**
    * Sample/Пример
    * 
    * {{MIKRON_COMMENTS entity=string id=int captcha=1 returnpage=string caption=string already=string listaddress=string}}
    * caption - заголовок списка имеющихся комментариев
    */

    function OperatingInstruction_MikronFavourites($parameters)
    {
        global $mikron;
        if(!$mikron->Users->Logged())
        {
            return false;
        }
        $entity = $parameters['entity'];
        $id = $parameters['id'];
        $captcha = true;
        $caption = 'Добавить в избранное';
        $already = 'В списке избранных';
        $returnpage = null;
        $listaddress = null;
        if(array_key_exists('returnpage', $parameters))
        {
            $returnpage = $parameters['returnpage'];
        }
        if(array_key_exists('caption', $parameters))
        {
            $caption = $parameters['caption'];
        }
        if(array_key_exists('already', $parameters))
        {
            $already = $parameters['already'];
        }
        if(array_key_exists('listaddress', $parameters))
        {
            $listaddress = $parameters['listaddress'];
        }
        if(isset($_GET['favent']) && isset($_GET['faventid']))
        {
            try
            {
                $entity = $_GET['favent'];
                $entity_id = (int)$_GET['faventid'];
                $mf = new MIKRON_FAVOURITE();
                $mf->entity->value = $entity;
                $mf->entityid->value = $entity_id;
                $mf->Save();
            }
            catch(Exception $ex)
            {
                
            }
        }
        $cr = new Criteria();
        $cr->Add(new Criterion('entity', $entity));
        $cr->Add(new Criterion('entityid', $id));
        $cr->Add(new Criterion('user', $mikron->Users->CurrentUser()->id()));
        $qr = $mikron->Queries->Query('MIKRON_FAVOURITE', null, $cr);
        if($qr->count() > 0)
        {
            if(!is_null($listaddress))
            {
                echo sprintf('<a href="%s" class="hiddentext">%s</a>', $listaddress, $already);
            }
            else
            {
                echo $already;
            }
        }
        else
        {
            $adr = "?favent=$entity&faventid=$id";
            echo sprintf('<a href="%s" class="hiddentext">%s</a>', $adr, $caption);
        }
        
    }

?>